//
//  LoadCourseDataManager.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-26.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//

#import "LoadCourseDataManager.h"
#import "ASIHTTPRequest.h"

static LoadCourseDataManager *_loadCourseInstance;

@implementation LoadCourseDataManager

+ (id)shareInstance
{
    if (!_loadCourseInstance)
    {
        _loadCourseInstance = [[LoadCourseDataManager alloc] init];
    }
    return _loadCourseInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.courseData = [[NSMutableArray alloc] init];
    }
    return self;
}
//读取网络数据
- (void)loadDataFromInternet
{
    NSString *urlString = @"http://so.open.163.com/movie/2/getPlays4Ipad.htm";
    NSURL *url = [NSURL URLWithString:urlString];
    NSLog(@"11!!!!!!%@",url);
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
//        NSLog(@"xxxxx%@",request.responseData);
        NSArray *courseArray = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *courseDic in courseArray)
        {
            CourseModel *model = [[CourseModel alloc] init];
            model.description = [courseDic objectForKey:@"description"];
            model.director = [courseDic objectForKey:@"director"];
            model.imagePath = [courseDic objectForKey:@"imgpath"];
            model.includeVirtual = [courseDic objectForKey:@"include_virtual"];
            model.playcount = [courseDic objectForKey:@"playcount"];
            model.plid = [courseDic objectForKey:@"plid"];
            model.school = [courseDic objectForKey:@"school"];
            model.source = [courseDic objectForKey:@"source"];
            model.subtitle = [courseDic objectForKey:@"subtitle"];
            model.tags = [courseDic objectForKey:@"tags"];
            model.title = [courseDic objectForKey:@"title"];
            model.type = [courseDic objectForKey:@"type"];
            model.updatedPlaycount = [courseDic objectForKey:@"updated_playcount"];
            //plid每一位转化成整型再相加
//            NSInteger count = 0;
            NSString *str = nil;
            NSInteger totle = 0;
            for (int i = 0; i < model.plid.length; i++)
            {
                char c = [model.plid characterAtIndex:i];
                NSNumber *number = [NSNumber numberWithChar:c];
                if (str == nil)
                {
                    NSInteger tempNum = [number integerValue];
                    str = [NSString stringWithFormat:@"%0.2d", tempNum];
                }
                else
                {
                    NSInteger tempNum = [number integerValue];
                    str = [str stringByAppendingFormat:@"%0.2d", tempNum];
                }
                if (i % 3 == 2)
                {
                    totle += [str integerValue];
                    str = nil;
                }
            }
            model.indentify = totle + [model.playcount integerValue];
//            NSLog(@"==== + %d + ====", model.indentify);
            
            [self.courseData addObject:model];
        }
        //获取完后推出主视图
        [[NSNotificationCenter defaultCenter] postNotificationName:kTurnToMainViewNotification object:nil];
    }];
    
    [request startAsynchronous];
    
}

#pragma mark --
#pragma mark loadCoursData
- (void)loadDetailCourseDataWith:(NSString *)urlString
{
    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setCompletionBlock:^{
        //json解析
        NSDictionary *courseDataDic = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
        CourseModel *model =[[CourseModel alloc] init];
        //取数据模型
        model.description = [courseDataDic objectForKey:@"description"];
        model.director = [courseDataDic objectForKey:@"director"];
        model.imagePath = [courseDataDic objectForKey:@"imgpath"];
        model.includeVirtual = [courseDataDic objectForKey:@"include_virtual"];
        model.playcount = [courseDataDic objectForKey:@"playcount"];
        model.plid = [courseDataDic objectForKey:@"plid"];
        model.school = [courseDataDic objectForKey:@"school"];
        model.source = [courseDataDic objectForKey:@"source"];
        model.subtitle = [courseDataDic objectForKey:@"subtitle"];
        model.tags = [courseDataDic objectForKey:@"tags"];
        model.title = [courseDataDic objectForKey:@"title"];
        model.updatedPlaycount = [courseDataDic objectForKey:@"updated_playcount"];
        //plid每一位转化成整型再相加
        //            NSInteger count = 0;
        NSString *str = nil;
        NSInteger totle = 0;
        for (int i = 0; i < model.plid.length; i++)
        {
            char c = [model.plid characterAtIndex:i];
            NSNumber *number = [NSNumber numberWithChar:c];
            if (str == nil)
            {
                NSInteger tempNum = [number integerValue];
                str = [NSString stringWithFormat:@"%0.2d", tempNum];
            }
            else
            {
                NSInteger tempNum = [number integerValue];
                str = [str stringByAppendingFormat:@"%0.2d", tempNum];
            }
            if (i % 3 == 2)
            {
                totle += [str integerValue];
                str = nil;
            }
        }
        model.indentify = totle + [model.playcount integerValue];
        //            NSLog(@"==== + %d + ====", model.indentify);
        

        
        //取视频模型
        NSArray *videoArray = [courseDataDic objectForKey:@"videoList"];
        NSMutableArray *historyArray = [NSMutableArray arrayWithArray:[self loadHistoryData]];
        BOOL flag = NO;
        CourseModel *tempSaveModel = nil;
        for (CourseModel *tempModel in historyArray)
        {
            if ([tempModel.title isEqualToString:model.title])
            {
                flag = YES;
                tempSaveModel = tempModel;
            }
        }
        
        if (flag)
        {
            model = tempSaveModel;
        }
        else
        {
            for (NSDictionary *videoDic in videoArray)
            {
                CourseVideoModel *videoModel = [[CourseVideoModel alloc] init];
                videoModel.commentid = [videoDic objectForKey:@"commentid"];
                videoModel.imgpath = [videoDic objectForKey:@"imgpath"];
                videoModel.iosshow = [videoDic objectForKey:@"iosshow"];
                videoModel.m3u8size = [videoDic objectForKey:@"m3u8size"];
                videoModel.m3u8sizeOrigin = [videoDic objectForKey:@"m3u8sizeOrigin"];
                videoModel.mid = [videoDic objectForKey:@"mid"];
                videoModel.mlength = [videoDic objectForKey:@"mlength"];
                videoModel.mp4size = [videoDic objectForKey:@"mp4size"];
                videoModel.mp4sizeOrigin = [videoDic objectForKey:@"mp4sizeOrigin"];
                videoModel.pnumber = [videoDic objectForKey:@"pnumber"];
                videoModel.protoVersion = [videoDic objectForKey:@"protoVersion"];
                videoModel.repovideourl = [videoDic objectForKey:@"repovideourl"];
                videoModel.repovideourlmp4 = [videoDic objectForKey:@"repovideourlmp4"];
                
                videoModel.subtitle = [videoDic objectForKey:@"subtitle"];
                videoModel.subtitleLanguage = [videoDic objectForKey:@"subtitle_language"];
                videoModel.title = [videoDic objectForKey:@"title"];
                videoModel.weburl = [videoDic objectForKey:@"weburl"];
                
                [model.videoList addObject:videoModel];
            }
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kDetailCourseNotification object:model];
        
    }];
    
    [request startAsynchronous];
}

- (NSArray *)loadRecommondData
{
    NSMutableArray *recommondCourses = [[NSMutableArray alloc] init];
    
    //获取头图（今日推荐）
    for (CourseModel *model in self.courseData)
    {
        if ([model.type isEqualToString:@"头图"])
        {
            [recommondCourses addObject:model];
        }
    }
    
    return recommondCourses;
}

#pragma mark --
#pragma mark Bookmark 归档
- (NSString *)getBookmarkPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    return [path stringByAppendingPathComponent:@"bookmark.archiver"];
}

- (NSArray *)loadBookmarkData
{
    
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getBookmarkPath]];
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
    NSMutableArray *readModels = [unArchiver decodeObjectForKey:@"kBookmarkDatas"];
    
    return readModels;
}

- (void)writeDataToBookmarkArchiverWithArray:(NSMutableArray *)dataModels
{
    NSMutableData *datas = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
    [archiver encodeObject:dataModels forKey:@"kBookmarkDatas"];
    [archiver finishEncoding];
    [datas writeToFile:[self getBookmarkPath] atomically:YES];
}

- (void)writeDataToBookmarkArchiverWithModel:(CourseModel *)model
{
    //先读取本地文件
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getBookmarkPath]];
    if (readDatas == nil)
    {
        NSMutableArray *dataModels = [[NSMutableArray alloc] init];
        [dataModels addObject:model];
        NSMutableData *datas = [NSMutableData data];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
        [archiver encodeObject:dataModels forKey:@"kBookmarkDatas"];
        [archiver finishEncoding];
        [datas writeToFile:[self getBookmarkPath] atomically:YES];
    }
    else
    {
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
        NSMutableArray *readModels = [unArchiver decodeObjectForKey:@"kBookmarkDatas"];
        //判断是否已收藏
        BOOL isHvaeBookmarked = NO;
        for (CourseModel *tempmodel in readModels)
        {
            NSLog(@"bookmark =====>> %@ ", model.title);
            if ([tempmodel.title isEqualToString:model.title])
            {
                isHvaeBookmarked = YES;
                break;
            }
        }
        //如果没有收藏
        if (!isHvaeBookmarked)
        {
            [readModels insertObject:model atIndex:0];
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kBookmarkDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getBookmarkPath] atomically:YES];
        }
        
    }//else ---> if (readDatas == nil)
    
}

#pragma mark --
#pragma mark History 归档
- (NSString *)getHistoryPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    return [path stringByAppendingPathComponent:@"history.archiver"];
}

- (NSArray *)loadHistoryData
{
    
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getHistoryPath]];
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
    NSMutableArray *dataModels = [unArchiver decodeObjectForKey:@"kHistoryDatas"];
    
    return dataModels;
}

- (void)writeToHistoryArchiverWithModel:(CourseModel *)courseModel
{
    //先读取本地文件
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getHistoryPath]];
    if (readDatas == nil)
    {
        NSMutableArray *dataModels = [[NSMutableArray alloc] init];
        [dataModels addObject:courseModel];
        NSMutableData *datas = [NSMutableData data];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
        [archiver encodeObject:dataModels forKey:@"kHistoryDatas"];
        [archiver finishEncoding];
        [datas writeToFile:[self getHistoryPath] atomically:YES];
    }
    else
    {
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
        NSMutableArray *readModels = [unArchiver decodeObjectForKey:@"kHistoryDatas"];
        //判断是否已有记录
        BOOL isHvaeHistory = NO;
        NSInteger index = 0;
        for (int i = 0; i < readModels.count; i++)
        {
            CourseModel *model = readModels[i];
            if ([model.title isEqualToString:courseModel.title])
            {
                isHvaeHistory = YES;
                index = i;
                break;
            }
            
        }
        
        //如果有记录
        if (isHvaeHistory)
        {
            [readModels removeObjectAtIndex:index];
            [readModels insertObject:courseModel atIndex:0];
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kHistoryDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getHistoryPath] atomically:YES];
        }
        else//如果没有记录
        {
            [readModels insertObject:courseModel atIndex:0];
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kHistoryDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getHistoryPath] atomically:YES];
        }
        
    }//else ---> if (readDatas == nil)
    
}

- (void)writeToHistoryArchiverWithArray:(NSMutableArray *)dataModels
{
    NSMutableData *datas = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
    [archiver encodeObject:dataModels forKey:@"kHistoryDatas"];
    [archiver finishEncoding];
    [datas writeToFile:[self getHistoryPath] atomically:YES];
}



#pragma mark --
#pragma Download 归档
- (NSString *)getDownloadPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    return [path stringByAppendingPathComponent:@"download.archiver"];
}

- (NSArray *)loadDownloadData
{
    
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getDownloadPath]];
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
    NSMutableArray *dataModels = [unArchiver decodeObjectForKey:@"kDownloadDatas"];
    
    return dataModels;
}

- (void)writeToDownloadArchiverWithArray:(NSMutableArray *)array
{
    NSMutableData *datas = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
    [archiver encodeObject:array forKey:@"kDownloadDatas"];
    [archiver finishEncoding];
    [datas writeToFile:[self getDownloadPath] atomically:YES];
}


- (void)writeToDownloadArchiverWithModel:(CourseModel *)courseModel
{
    //先读取本地文件
    NSData *readDatas = [NSData dataWithContentsOfFile:[self getDownloadPath]];
    if (readDatas == nil)
    {
        NSMutableArray *dataModels = [[NSMutableArray alloc] init];
        [dataModels addObject:courseModel];
        NSMutableData *datas = [NSMutableData data];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
        [archiver encodeObject:dataModels forKey:@"kDownloadDatas"];
        [archiver finishEncoding];
        [datas writeToFile:[self getDownloadPath] atomically:YES];
    }
    else
    {
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readDatas];
        NSMutableArray *readModels = [unArchiver decodeObjectForKey:@"kDownloadDatas"];
        //判断是否已有记录
        BOOL isHvaeSelectedToDownload = NO;
        NSInteger index = 0;
        for (int i = 0; i < readModels.count; i++)
        {
            CourseModel *model = readModels[i];
            if ([model.title isEqualToString:courseModel.title])
            {
                isHvaeSelectedToDownload = YES;
                index = i;
                break;
            }
            
        }
        
        //如果有记录
        if (isHvaeSelectedToDownload)
        {
            for (CourseVideoModel *videoModel in courseModel.videoList)
            {
                CourseModel *tempReadModel = readModels[index];
                for (CourseVideoModel *downModel in tempReadModel.videoList)
                {
                    if ([videoModel.pnumber isEqualToNumber:downModel.pnumber])
                    {
                        
                        downModel.isSelectedToDownload = videoModel.isSelectedToDownload;
                        downModel.isDownloaded = videoModel.isDownloaded;
                        downModel.isDownloading = videoModel.isDownloading;
                        downModel.isDownloadPause = videoModel.isDownloadPause;
                        
                    }//if ([videoModel.pnumber isEqualToNumber:downModel.pnumber])
                }
            }
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kDownloadDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getDownloadPath] atomically:YES];
        }
        else//如果没有记录
        {
            [readModels addObject:courseModel];
            NSMutableData *datas = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:datas];
            [archiver encodeObject:readModels forKey:@"kDownloadDatas"];
            [archiver finishEncoding];
            [datas writeToFile:[self getDownloadPath] atomically:YES];
        }
        
    }//else ---> if (readDatas == nil)
    
}









@end
